package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
//@ControllerAdvice(annotations = {RestController.class, Controller.class})
//@ResponseBody
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
public class GlobalExceptionHandler {

    //数据库抛出的异常原因可能有很多. 主键  唯一  非空约束  外键约束
    @ExceptionHandler({SQLIntegrityConstraintViolationException.class})
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.info(ex.getMessage()); //

        //获取异常信息
        if (ex.getMessage().contains("Duplicate entry")) {
            //判断异常信息是否为唯一约束异常
            String[] split = ex.getMessage().split(" ");
            //如果是,则截取异常信息中的用户名,并返回
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }

    @ExceptionHandler({CustomException.class})
    public R customExceptionHandler(CustomException ex){
        return R.error(ex.getMessage());
    }

}
